package _02_linked_list;

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * @author: mornd
 * @dateTime: 2023/5/31 - 14:26
 * 双向链表（头，尾共两哨兵，头哨兵.prev = 尾哨兵.next = null）
 */
public class DoublyLinkedListSentinel<E> implements Iterable<E> {
    // 头哨兵
    private final Node<E> head;
    // 尾哨兵
    private final Node<E> tail;

    /**
     * 构造器，初始化头，尾哨兵
     */
    public DoublyLinkedListSentinel() {
        this.head = new Node<>(null, null, null);
        this.tail = new Node<>(null, null, null);
        // 头尾互指
        this.head.next = this.tail;
        this.tail.prev = this.head;
    }

    /**
     * 根据下标获取元素
     * @param index
     * @return
     */
    public E get(int index) {
        if(index < 0) {
            throw illegalIndex(index);
        }
        Node<E> node = findNode(index);
        if(node == null) {
            throw illegalIndex(index);
        }
        return node.value;
    }

    public Node<E> getFirst() {
        Node<E> next = head.next;
        if(next == tail) {
            throw new NoSuchElementException();
        }
        return next;
    }

    public Node<E> getLast() {
        Node<E> prev = tail.prev;
        if(prev == head) {
            throw new NoSuchElementException();
        }
        return prev;
    }

    /**
     * 根据下标找元素，未找到返回 null，可以根据-1找到头哨兵，但是无法找到尾哨兵
     * @param index
     * @return
     */
    private Node<E> findNode(int index) {
        // 可以根据下标 -1 找到头，但是无法找到尾
        int i = -1;
        for (Node<E> p = head; p != tail; p = p.next, i++) {
            if(i == index) {
                return p;
            }
        }
        return null;
    }

    public E set(int index, E e) {
        if(index < 0) {
            throw illegalIndex(index);
        }
        Node<E> node = findNode(index);
        if(node == null) {
            throw illegalIndex(index);
        }
        E value = node.value;
        node.value = e;
        return value;
    }

    /**
     * 插入元素至指定的下标
     * @param index
     * @param e
     */
    public void insert(int index, E e) {
        Node<E> prev = findNode(index - 1);
        if(prev == null) {
            throw illegalIndex(index);
        }
        Node<E> next = prev.next;
        Node<E> newNode = new Node<>(prev, e, next);
        prev.next = newNode;
        next.prev = newNode;
    }

    public void add(E e) {
        addLast(e);
    }

    public void addFirst(E e) {
        insert(0, e);
    }

    public void addLast(E e) {
        Node<E> prev = tail.prev;
        Node<E> newNode = new Node<>(prev, e, tail);
        prev.next = newNode;
        tail.prev = newNode;
    }

    public void remove(int index) {
        if(index < 0) {
            throw illegalIndex(index);
        }
        Node<E> node = findNode(index);
        if(node == null) {
            throw illegalIndex(index);
        }
        Node<E> prev = node.prev;
        Node<E> next = node.next;
        prev.next = next;
        next.prev = prev;
    }

    public void removeFirst() {
        remove(0);
    }

    public void removeLast() {
        Node<E> removed = tail.prev;
        if(removed == head) {
            throw new NoSuchElementException();
        }
        Node<E> prev = removed.prev;
        prev.next = tail;
        tail.prev = prev;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("[");
        for (Node<E> p = head.next; p != tail; p = p.next) {
            sb.append(p.value);
            if(p.next != tail) {
                sb.append(",");
            }
        }
        return sb.append("]").toString();
    }

    /**
     * 下标不合法异常
     * @param index
     * @return
     */
    private IllegalArgumentException illegalIndex(int index) {
        return new IllegalArgumentException(String.format("下标 %d 不合法", index));
    }

    @Override
    public Iterator<E> iterator() {
        return new Itr();
    }

    private class Itr implements Iterator<E> {
        Node<E> p = head.next;
        @Override
        public boolean hasNext() {
            return p != tail;
        }

        @Override
        public E next() {
            E value = p.value;
            p = p.next;
            return value;
        }
    }

    /**
     * 节点元素
     */
    private static class Node<E> {
        Node<E> prev;
        E value;
        Node<E> next;

        public Node(Node<E> prev, E value, Node<E> next) {
            this.prev = prev;
            this.value = value;
            this.next = next;
        }

        @Override
        public String toString() {
            return String.valueOf(value);
        }
    }
}
